import * as GUI from '@babylonjs/gui'
import { Inspector } from '@babylonjs/inspector'
import { YkBabylonScene } from './create3D'
import { startCharging } from './animations.ts'
import { useSgesMAStore } from './MountainGesCalA.ts'
import { storeToRefs } from 'pinia'

const store = useSgesMAStore()

const {
  displayInfo,
  massBlock,
  lengthBlock,
  widthBlock,
  heightBlock,
  frictionFactor
} = storeToRefs(store)

// 上次更新时间
let lastUpdateTime: number = 0

export const AddGUIControls = (ykScene: YkBabylonScene) => {
  const scene = ykScene.scene
  const advancedTexture = GUI.AdvancedDynamicTexture.CreateFullscreenUI('myUI')

  // 创建FPS文本框
  const fpsText = new GUI.TextBlock()
  fpsText.text = 'FPS: 0'
  fpsText.width = '100px'
  fpsText.height = '30px'
  fpsText.color = ykScene.textColor
  fpsText.fontSize = 14
  fpsText.horizontalAlignment = GUI.Control.HORIZONTAL_ALIGNMENT_RIGHT
  fpsText.verticalAlignment = GUI.Control.VERTICAL_ALIGNMENT_TOP
  advancedTexture.addControl(fpsText)

  const button2 = GUI.Button.CreateSimpleButton('but2', '调试信息')
  button2.width = '100px'
  button2.height = '30px'
  button2.cornerRadius = 5
  button2.color = ykScene.textColor

  button2.onPointerUpObservable.add(function() {
    // 尝试捕获可能的网络错误
    try {
      Inspector.Show(scene, { embedMode: true })
    } catch (e) {
      console.warn('Inspector加载失败，可能由于字体服务不可用:', e)
      // 可以考虑显示一个简化版的调试信息
    }
  })
  button2.horizontalAlignment = GUI.Control.HORIZONTAL_ALIGNMENT_LEFT
  button2.verticalAlignment = GUI.Control.VERTICAL_ALIGNMENT_TOP
  advancedTexture.addControl(button2)


  const button7 = GUI.Button.CreateSimpleButton('but7', '开始储能')
  button7.width = '100px'
  button7.height = '30px'
  button7.cornerRadius = 5
  button7.color = ykScene.textColor
  button7.onPointerUpObservable.add(() => {
    startCharging(ykScene)
  })
  button7.left = '0px'
  button7.top = '30px'
  button7.horizontalAlignment = GUI.Control.HORIZONTAL_ALIGNMENT_LEFT
  button7.verticalAlignment = GUI.Control.VERTICAL_ALIGNMENT_TOP
  advancedTexture.addControl(button7)

  // 监听场景渲染事件，检查是否有选中的物体
  scene.onAfterRenderObservable.add(() => {
    // 获取当前时间
    const currentTime = Date.now()

    // 如果距离上次更新时间不足1秒，直接返回
    if (currentTime - lastUpdateTime < 300) {
      return
    }

    // 更新上次更新时间
    lastUpdateTime = currentTime

    // 更新FPS显示
    const fps = scene.getEngine().getFps()
    fpsText.text = `FPS: ${Math.round(fps)}`

    // 检查是否有选中的物体
    if (ykScene.customData.selected) {
      const _length = ykScene.customData.selected.length
      const name = ykScene.customData.selected[_length - 1]
      const selectedMesh = scene.getMeshByName(name)

      // 添加调试信息
      // console.log('Selected object:', name)
      // console.log('Selected mesh exists:', !!selectedMesh)

      if (name && name.startsWith('Cart') && selectedMesh) {
        displayInfo.value = {
          name: '载重小车',
          subdomain: [
            {
              title: '物理属性',
              质量: massBlock.value,
              长度: { value: lengthBlock.value, editable: true, ref: 'lengthBlock' },
              宽度: { value: widthBlock.value, editable: true, ref: 'widthBlock' },
              高度: { value: heightBlock.value, editable: true, ref: 'heightBlock' },
              摩擦系数: { value: frictionFactor.value, editable: true, ref: 'frictionFactor' }
            },
            {
              title: '运动属性',
              坐标: selectedMesh.position.asArray(),
              旋转: selectedMesh.rotation.asArray(),
              速度: selectedMesh.physicsBody?.getLinearVelocity().asArray()
            }
          ]
        }
        console.log('Set displayInfo with object data')
      } else if (name && name.startsWith('发电机')) {
        // 如果选中的物体不匹配条件，清除信息
        displayInfo.value = {
          name: '升降系统',
          subdomain: [
            {
              title: '物理属性',
              转速: 600,
              电压: 6000
            }
          ]
        }
        // console.log('Set displayInfo to empty (object not matching conditions)');
      } else {
        displayInfo.value = {}
      }

    } else {
      // 如果没有选中物体，清除信息
      displayInfo.value = {}
      // console.log(`选中的网格名称为：${name}`)
      // console.log('Set displayInfo to empty (no selection)');
    }
  })
}
